<template>
  <div class="user-menu">
    <el-dropdown @command="handleCommand">
      <div class="user-info">
        <el-avatar :size="32" :src="userAvatar" class="user-avatar">
          {{ userInitials }}
        </el-avatar>
        <span class="user-name" v-if="!isMobile">{{ userName }}</span>
        <el-icon class="dropdown-icon" v-if="!isMobile">
          <arrow-down />
        </el-icon>
      </div>
      
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="profile">
            <el-icon><user /></el-icon>
            个人中心
          </el-dropdown-item>
          <el-dropdown-item command="settings">
            <el-icon><setting /></el-icon>
            系统设置
          </el-dropdown-item>
          <el-dropdown-item divided command="logout">
            <el-icon><switch-button /></el-icon>
            退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores/appStore'
import { ArrowDown, User, Setting, SwitchButton } from '@element-plus/icons-vue'

// 定义组件名称
defineOptions({
  name: 'UserMenu'
})

// 定义props
const props = defineProps({
  isMobile: {
    type: Boolean,
    default: false
  }
})

// 获取路由和store实例
const router = useRouter()
const appStore = useAppStore()

// 计算属性
const userAvatar = computed(() => appStore.user?.avatar || '')
const userName = computed(() => appStore.user?.name || '用户')
const userInitials = computed(() => {
  const name = appStore.user?.name || 'U'
  return name.charAt(0).toUpperCase()
})

// 方法
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      // 跳转到个人中心
      router.push('/system/profile')
      break
    case 'settings':
      // 跳转到系统设置
      router.push('/system/settings')
      break
    case 'logout':
      // 退出登录
      handleLogout()
      break
  }
}

const handleLogout = () => {
  appStore.resetToken()
  router.push('/login')
}
</script>

<style scoped>
.user-menu {
  display: flex;
  align-items: center;
  height: 100%;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.user-avatar {
  background-color: #1890ff;
  color: white;
}

.user-name {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
}

.dropdown-icon {
  font-size: 12px;
  color: #999;
}

@media (max-width: 767px) {
  .user-info {
    padding: 4px;
  }
  
  .user-name {
    display: none;
  }
  
  .dropdown-icon {
    display: none;
  }
}
</style>